<?php
/**
 * 邮件
 * 
 * Created	: 2011-05-18
 * Modified : 2011-05-18
 * @author  : 陈立强
 */
class Mail
{
	public static $cfg = null;
	public static $cfgName = 'build/mail';
	
	/**
	 * 获取新邮件的数量
	 * @param int $uid
	 * @param boolean $interface 是否客户端接口调用 
	 */
	public static function getNewMailCounts($uid, $interface=false) 
	{
		global $DB, $L, $G;
		$where = 'to_uid='.$uid.' AND isread=0';
		$cnt = $DB->getCount('mail', $where);
		
		if ($interface) {
			return array(
				'val'		=> true,
				'counts'	=> $cnt,
			);
		} else {
			return $cnt;
		}
	}

	/**
	 * 发送信件
	 * @param int $uid 当前发邮件用户
	 * @param string|array $to_user 接收人的昵称或接收人信息(含$uid和$nickname昵称)
	 * @param string $content 邮件内容
	 * @param int $type 邮件类型:1-系统,2-普通
	 * @param array $attachment 附件(多个附件,多维数组)
	 */
	public static function send($uid, $to_user, $content, $type=2, $attachment=null)
	{
		global $DB, $L, $G;
		
		if (is_array($to_user)) {
			$to_uid = $to_user['uid'];
			$to_nickname = $to_user['nickname'];
		} else {
			$to_nickname = $to_user;
			$sql = 'SELECT uid FROM user WHERE nickname=\''.addslashes($to_nickname).'\'';
			$to_uid = $DB->getValue($sql);
		}
		if (!$to_uid) {
			return array(
				'val' => false,
				'msg' => $L['user_not_exists']
			);
		}
		if ($uid == $to_uid) {
			return array(
				'val' => false,
				'msg' => $L['cannot_send_mail_to_self']
			);
		}
		
		$DB->beginTransaction();
		
		if (is_array($attachment) && $attachment) {
			$attachCounts = count($attachment);
			if ($attachCounts > $G['mail_max_attachment']) {
				return array(
					'val' => false,
					'msg' => $L['mail_attachment_too_much']
				);
			}
		}
		
		if (empty($attachment)) {
			$attachment = '';
		} else {
			$attachment = json_encode($attachment);
		}
		
		$data = array(
			'uid'			=> $uid,
			'nickname'		=> $_SESSION['nickname'],
			'to_uid'		=> $to_uid,
			'to_nickname'	=> $to_nickname,
			'content'		=> $content,
			'type'			=> $type,
			'send_time'		=> time(),
			'isread'		=> 0,
			'attachment'	=> $attachment
		);
		$ret = $DB->insert('mail', $data);
		
		// 用户在线,发送聊天频道的信息
		if ($ret && User::isOnline($to_uid)) {
			global $m;
			$m->set('newmail-'.$to_uid, true);
		}
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
		} else {
			$DB->rollBack();
			$result['msg'] = isset($msg) ? $msg : $L['Failure'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('mail_send', $str);
		}

		return $result;
	}
	
	/**
	 * 读取信件
	 * @param int $uid
	 * @param int $m_id
	 */
	public static function read($uid, $m_id)
	{
		global $DB, $L, $G;
		
		$where = 'm_id='.$m_id;
		$sql = 'SELECT * FROM mail WHERE '.$where;
		$mail = $DB->getValue($sql);
		if (!$mail || ($mail['uid']!=$uid && $mail['to_uid']!=$uid)) {
			return array(
				'val' => false,
				'msg' => $L['mail_not_exists']
			);
		}
		$now = time();
		// 有附件判断是否过期
		if ($mail['attachment'] && ($now-$mail['send_time']) >= $G['mail_attachment_expire']) {
			$attachmentExpire = true;
		} else {
			$attachmentExpire = false;
		}
		
		// 接收邮件未读,更改状态为已读
		if (!$mail['isread'] && $uid==$mail['to_uid']) {
			$data = array(
				'isread' => 1
			);
			if ($attachmentExpire) {
				$data['attachment'] = '';
			}
			$ret = $DB->update('mail', $data, $where);
			$mail['isread'] = true;
		} else if ($attachmentExpire) {
			$data = array(
				'attachment' => ''
			);
			$ret = $DB->update('mail', $data, $where);
		}
		
		return $mail;
	}
	
	/**
	 * 删除所有已读无附件邮件
	 * @param int $uid
	 */
	public static function deleteAll($uid)
	{
		global $DB, $L, $G;
		
		$sql = 'DELETE FROM mail WHERE to_uid='.$uid.' AND isread=1 AND attachment=\'\'';
		$ret = $DB->exeSql($sql);
		if ($ret !== false) {
			$ret = true;
		}
		
		if ($ret) {
			return array(
				'val' => true
			);
		} else {
			return array(
				'val' => false,
				'msg' => $L['Failure_Delete']
			);
		}
	}
	
	/**
	 * 删除邮件
	 * @param int|string $uid
	 * @param int|string $m_id 邮件ID
	 */
	public static function delete($uid, $m_id)
	{
		global $DB, $L, $G;
		
		$where = 'm_id='.$m_id;
		
		$sql = 'SELECT uid,to_uid FROM mail WHERE '.$where;
		$mail = $DB->getValue($sql);
		
		if (!$mail || $mail['to_uid']!=$uid) {
			return array(
				'val' => true,
				'msg' => $L['mail_not_exists']
			);
		}
		
		$msg = '';
		$sql = 'DELETE FROM mail WHERE '.$where;
		$ret = $DB->exeSql($sql);
		
		if ($ret) {
			return array(
				'val' => true
			);
		} else {
			return array(
				'val' => false,
				'msg' => $L['Failure_Delete']
			);
		}
	}
	
	/**
	 * 获取信件列表
	 * @param int $uid
	 * @param int $pageNo
	 * @param int $type 1-收件箱,2-发件箱
	 */
	public static function getList($uid, $pageNo=1)
	{
		global $DB, $L, $G;
		
		$pageNo = (int)$pageNo;
		$pageSize = $G['mail_page_size'];
		
		$where = 'to_uid='.$uid;
		$sql = 'SELECT * FROM mail WHERE '.$where.' ORDER BY m_id DESC';
		
		if ($pageNo > 0) {
			$total = $DB->getCount('mail', $where);
			$pageCounts = ceil($total/$pageSize);
			if ($pageNo > $pageCounts) {
				$pageNo = 1;
			}
			$start = ($pageNo-1) * $pageSize;
			$sql .= ' LIMIT '.$start.', '.$pageSize;
			$data['total'] = $total;
			$data['cur_page'] = $pageNo;
			$data['max_page'] = $pageCounts;
		}
		
		$list = $DB->getList($sql);
//		if (!is_array($list)) {
//			$list = array();
//		}
		
		$itemList = C('item/item_list');
		
		foreach ($list as $k=>$v) {
			if (!$v['attachment']) {
				$list[$k]['attachment'] = array();
				continue;
			}
			$attachment = json_decode($v['attachment'], true);
			if (is_array($attachment))
			foreach ($attachment as $kk=>$vv) {
				$itemCfg = $itemList[$vv['item_id']];
				$attachment[$kk]['title'] = $itemCfg['title'];
				if ($itemCfg['type'] == 53) {
					$attachment[$kk]['lvl'] = $itemCfg['lvl'];
					$vv['attr'] = json_decode($vv['attr'], true);
					$attachment[$kk]['attr'] = array();
					foreach ($vv['attr'] as $abi_id=>$abi_val) {
						$abiCfg = $itemList[$abi_id];
						$attachment[$kk]['attr'][] = array(
							'abi_id' => $abi_id,
							'title'	 => $abiCfg['title'],
							'abi_val' => $abi_val
						);
					}
				}
			}
			$list[$k]['attachment'] = $attachment;
		}
		
		$data['list'] = $list;
		
		return array(
			'val'  => true,
			'data' => $data
		);
	}
	
	/**
	 * 获取附件
	 * @param int $uid
	 * @param int $m_id 邮件ID
	 * @param int $key 对应收取哪个附件的顺序ID,单独领取:0~X的KEY,全部领取:-1
	 */
	public static function fetchAttachment($uid, $m_id, $key=-1)
	{
		global $DB, $L, $G;
		
		$mail = self::read($uid, $m_id);
		// 不是自己的邮件,不能获取附件
		if (!$mail || $mail['to_uid']!=$uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		$list = json_decode($mail['attachment'], true);
		
		$DB->beginTransaction();
		
		$itemList = C('item/item_list');
		foreach ($list as $k=>$v) {
			// 指定只收取哪个附件,则其它附件跳过处理
			if ($key > -1 && $k!=$key) {
				continue;
			}
			$cfg = $itemList[$v['item_id']];
			switch ($cfg['type']) {
				// 牧场种子/树苗/幼仔及产品
				case 1:// 作物
				case 2:// 种子
				case 3:// 水果
				case 4:// 树苗
				case 6:// 动物幼仔
				case 7:// 动物产品
				case 11:// 金属
				case 12:// 木材
				case 13:// 石料
				case 14:// 毛皮
				case 51:// 辅材
					$data = array(
						'title'		=> $cfg['title'],
						'item_id'	=> $v['item_id'],
						'item_type' => $cfg['type'],
						'num'		=> $v['num'],
						'quality'	=> (int)$v['quality'],
						'lvl'		=> $cfg['lvl']
					);
					$ret = Depot::in($uid, $data);
					if ($ret['val']) {
						$depot_id = $ret['data']['depot_id'];
					} else {
						$msg = $ret['msg'];
					}
					$ret = $ret['val'];
					break;
					
				case 31:// 农田道具
				case 32:// 果林道具
				case 33:// 养殖道具
				case 34:// 采集道具
					$data = array(
						'title'		=> $cfg['title'],
						'item_id'	=> $v['item_id'],
						'item_type' => $cfg['type'],
						'num'		=> $v['num'],
						'quality'	=> (int)$v['quality'],
						'lvl'		=> $cfg['lvl']
					);
					$ret = Depot::in($uid, $data);
					if ($ret['val']) {
						$depot_id = $ret['data']['depot_id'];
					} else {
						$msg = $ret['msg'];
					}
					$ret = $ret['val'];
					break;
					
				case 52:// 宝石
					$data = array(
						'item_id'	=> $v['item_id'],
						'item_type' => $cfg['type'],
						'title'		=> $cfg['title'],
						'num'		=> 1,
						'quality'	=> 0,
						'stack'		=> 0,
						'lvl'		=> $cfg['lvl'],
						'color'		=> $v['color'],
						'part'		=> 0,
						'attr'		=> $v['attr'],
					);
					$ret = Bag::in($uid, $data);
					if ($ret) {
						$bag_id = $ret;
					} else {
						$msg = Bag::$msg;
					}
					break;
					
				case 53:// 装备
					$data = array(
						'item_id'	=> $v['item_id'],
						'item_type' => $cfg['type'],
						'title'		=> $cfg['title'],
						'num'		=> 1,
						'quality'	=> 0,
						'stack'		=> 0,
						'lvl'		=> $cfg['lvl'],
						'color'		=> $v['color'],
						'part'		=> $v['part'],
						'inlay'		=> $v['inlay'],
						'attr'		=> $v['attr'],
					);
					$ret = Bag::in($uid, $data);
					if ($ret) {
						$bag_id = $ret;
					} else {
						$msg = Bag::$msg;
					}
					break;
					
				case 54:// 卡片
					$data = array(
						'item_id'	=> $v['item_id'],
						'item_type' => $cfg['type'],
						'title'		=> $cfg['title'],
						'num'		=> 1,
						'quality'	=> 0,
						'stack'		=> 0,
						'lvl'		=> $cfg['lvl'],
						'color'		=> 0,
						'part'		=> 0,
					);
					$ret = Bag::in($uid, $data);
					if ($ret) {
						$bag_id = $ret;
					} else {
						$msg = Bag::$msg;
					}
					break;
				
				case 62://宝箱
					$data = array(
						'item_id'	=> $v['item_id'],
						'item_type' => $cfg['type'],
						'title'		=> $cfg['title'],
						'num'		=> 1,
						'quality'	=> 0,
						'stack'		=> 0,
						'lvl'		=> $v['lvl'],
						'color'		=> 0,
						'part'		=> 0,
						'attr'		=> $v['attr'],
					);
					$ret = Bag::in($uid, $data);
					if ($ret) {
						$bag_id = $ret;
					} else {
						$msg = Bag::$msg;
					}
					break;
				
				case 99:// 金钱
					$sql = 'UPDATE user SET coin=coin+'.$v['num'].' WHERE uid='.$uid;
					$ret = $DB->exeSql($sql);
					break;
					
				case 101:// 烹饪食品
				case 102:// 饮料
				case 103:// 家具
					$data = array(
						'item_id'	=> $v['item_id'],
						'item_type' => $cfg['type'],
						'title'		=> $cfg['title'],
						'num'		=> 1,
						'stack'		=> 0,
						'quality'	=> $v['quality'],
						'main_mat_quality' => $v['main_mat_quality'],
						'lvl'		=> $v['lvl'],
					);
					$ret = Shop::depotIn($uid, $data);
					$ret = $ret['val'];
					if ($ret['val']) {
					} else {
						$msg = $ret['msg'];
					}
					$ret = $ret['val'];
					break;
				
				default:
					$ret = false;;
					break;
			}
		}
		
		if ($ret) {
			if ($key > -1) {
				unset($list[$key]);
				sort($list);
				$attachmentStr = json_encode($list);
				$data = array(
					'attachment' => $attachmentStr
				);
				$ret = $DB->update('mail', $data, 'm_id='.$m_id);
				$mail['attachment'] = $attachmentStr;
			} else {
				$sql = 'UPDATE mail SET attachment=\'\' WHERE m_id='.$m_id;
				$ret = $DB->exeSql($sql);
				$mail['attachment'] = '';
			}
		}
		
		$result['val'] = (boolean)$ret;
		if ($result['val']) {
			$DB->commit();
//			$result['data'] = $mail;
		} else {
			$DB->rollBack();
			if (isset($msg)) {
				$result['msg'] = $msg;
			} else {
				$result['msg'] = $L['Failure_Update'];
			}
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('mail_fetch_attachment', $str);
		}
		
		return $result;
	}
}










